﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YYNY.Tools;
using YYNY.Tools.Dao;
using System.IO;
using Newtonsoft.Json.Linq;

namespace YYNY.Controllers
{
    public class ProcessController : Controller
    {
        BaseDao dao = new BaseDao();
        // GET: Process
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult TemplateView()
        {
            return View("TemplateIndex");
        }

        public ActionResult ProcessTemplatTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,ProcTemplateId,NodeName,Content,Department,TempName,NodeNum" +
                        " ,ProStage" +
                        " FROM t_d_ProcTemplate" +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "ProcTemplateId", "NodeName", "Content", "Department", "TempName", "NodeNum", "ProStage" });
                SqlNum = "select count(ProcTemplateId) as TotalNum  FROM t_d_ProcTemplate  where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /ProcessController/ProcessTemplatTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }


        public ActionResult TemplateAdd()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                //map.Add("IsDelete", "0");
                //string InventoryId = map["InventoryId"].ToString();
                //map.Remove("InventoryId");

                dao.save("t_d_ProcTemplate", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult TemplateEdit()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                string ProcTemplateId = map["ProcTemplateId"].ToString();
                map.Remove("ProcTemplateId");

                dao.update("t_d_ProcTemplate", map, "ProcTemplateId=" + ProcTemplateId);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult TemplateDel()
        {
            string ProcTemplateId = Request.Form["ProcTemplateId"] == null ? null : Request.Form["ProcTemplateId"].ToString().Replace(" ", "");
            string sql = "Delete t_d_ProcTemplate where ProcTemplateId=" + ProcTemplateId;

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult ProcessInfo()
        {
            string sql = "select ProjectId,Name,ProjectCode,Type from t_d_ProjectInfo where IsDelete<>1";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "Name", "ProjectCode", "Type" });
            ViewBag.ProjectList = ProjectList;

            sql = "select UserId,UserName from t_d_User where Department<>'领导' and Department<>'开发者' and IsDelete<>1 order by Department";
            var UserList = dao.GetList(sql, new string[] { "UserId", "UserName" });
            ViewBag.UserList = UserList;

            string UserId= Request.Cookies["UserID"].Value;
            sql = "select * from o_Authority where UserId=" + UserId;
            var AuthList = dao.GetList(sql, new string[] { "Type", "Name", "UserId" });
            ViewBag.AuthList = AuthList;
            ViewBag.UserId = UserId;

            return View("ProcessInfo");
        }


        /// <summary>
        /// 点击单个文件的时候出现的页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ProcessInfoSingle()
        {
            string ProjectId = Request.QueryString["ProjectId"];
            string sql = "";
            sql = "select UserId,UserName from t_d_User where Department<>'领导' and Department<>'开发者' and IsDelete<>1 order by Department";
            var UserList = dao.GetList(sql, new string[] { "UserId", "UserName" });
            ViewBag.UserList = UserList;

            string UserId = Request.Cookies["UserID"].Value;
            sql = "select * from o_Authority where UserId=" + UserId;
            var AuthList = dao.GetList(sql, new string[] { "Type", "Name", "UserId" });
            ViewBag.AuthList = AuthList;
            ViewBag.UserId = UserId;
            ViewBag.ProjectId = ProjectId;

            //搜索流程名字
            string ProjectName = dao.GetString("t_d_projectinfo", "Name", "and ProjectId=" + ProjectId);
            ViewBag.ProjectName = ProjectName;

            return View("ProcessInfoSingle");
        }

        /// <summary>
        /// 个人任务
        /// </summary>
        /// <returns></returns>
        public ActionResult ProcessInfoUser()
        {
            string UserId = Request.Cookies["UserID"].Value;
            string sql = "SELECT a.ProjectId,b.ProjectCode,b.type," +
                " b.Name from o_Process a INNER JOIN t_d_ProjectInfo b ON a.ProjectId=b.projectId and b.IsDelete=0 " +
                " WHERE a.UserId=" + UserId + " AND a.NodeState<>'已完成'" +
                " GROUP BY a.ProjectId,b.projectCode,b.type,b.Name,b.projectId,b.ContrTime" +
                " ORDER BY b.projectId,b.ContrTime DESC";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "Name", "ProjectCode", "Type" });
            ViewBag.ProjectList = ProjectList;

            sql = "select UserId,UserName from t_d_User where Department<>'领导' and Department<>'开发者' and IsDelete<>1 order by Department";
            var UserList = dao.GetList(sql, new string[] { "UserId", "UserName" });
            ViewBag.UserList = UserList;

            
            sql = "select * from o_Authority where UserId=" + UserId;
            var AuthList = dao.GetList(sql, new string[] { "Type", "Name", "UserId" });
            ViewBag.AuthList = AuthList;
            ViewBag.UserId = UserId;

            return View("ProcessInfoUser");
        }

        public ActionResult ProcessAdd()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                map["UpdateTime"] = DateTime.Now.ToString();
                dao.save("o_Process", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        /// <summary>
        /// 获取整个项目的节点
        /// </summary>
        /// <returns></returns>
        public ActionResult GetProcess()
        {            
            string ProjectId = Request.Form["ProjectId"] == null ? null : Request.Form["ProjectId"].ToString();
            string State = Request.Form["State"] == null ? null : Request.Form["State"].ToString();
            string ProStage = Request.Form["ProStage"] == null ? null : Request.Form["ProStage"].ToString();

            string Condition = "";
            if (ProStage == "0")
            {
                Condition = "";
            }
            else
            {
                Condition = " and ProStage=" + ProStage;
            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            if (State == "全部")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where IsDelete=0 and ProjectId=" + ProjectId + Condition + " order by ProStage,NodeNum asc";
            }
            else if(State == "进行中")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where NodeState='进行中' and IsDelete=0 and ProjectId=" + ProjectId + Condition + " order by ProStage,NodeNum asc";
            }
            else if(State == "滞后")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where NodeState='滞后' and IsDelete=0 and ProjectId=" + ProjectId + Condition + " order by ProStage,NodeNum asc";
            }
            else if (State == "已完成")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where NodeState='已完成' and IsDelete=0 and ProjectId=" + ProjectId + Condition + " order by ProStage,NodeNum asc";
            }

            try
            {
                var ProcessList = dao.GetList(sql, new string[] { "ProcessId", "NodeName", "Department", "EndTime", "UpdateTime", "NodeNum", "NodeState", "ApplicationState", "UserName", "ProjectId" });           
                return Json(ProcessList);

            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
            
        }

        /// <summary>
        /// 获取单个项目的 仅仅属于个人的节点
        /// </summary>
        /// <returns></returns>
        public ActionResult GetProcessByUser()
        {
            string UserId = Request.Cookies["UserID"].Value;
            string ProjectId = Request.Form["ProjectId"] == null ? null : Request.Form["ProjectId"].ToString();
            string State = Request.Form["State"] == null ? null : Request.Form["State"].ToString();

            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            if (State == "全部")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where IsDelete=0 and ProjectId=" + ProjectId + " and UserId="+UserId+" order by NodeNum asc";
            }
            else if (State == "进行中")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where NodeState='进行中' and IsDelete=0 and ProjectId=" + ProjectId + " and UserId=" + UserId + " order by NodeNum asc";
            }
            else if (State == "滞后")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where NodeState='滞后' and IsDelete=0 and ProjectId=" + ProjectId + " and UserId=" + UserId + " order by NodeNum asc";
            }
            else if (State == "已完成")
            {
                sql = "select ProcessId,NodeName,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                    ",ApplicationState,NodeNum,NodeState,UserName,ProjectId from o_Process where NodeState='已完成' and IsDelete=0 and ProjectId=" + ProjectId + " and UserId=" + UserId + " order by NodeNum asc";
            }

            try
            {
                var ProcessList = dao.GetList(sql, new string[] { "ProcessId", "NodeName", "Department", "EndTime", "UpdateTime", "NodeNum", "NodeState", "ApplicationState", "UserName", "ProjectId" });
                return Json(ProcessList);

            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }

        }

        /// <summary>
        /// 获取单个节点详细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetProcessById()
        {
            string ProcessId = Request.Form["ProcessId"] == null ? null : Request.Form["ProcessId"].ToString();

            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            sql = "select ProcessId,NodeName,Content,Department,CONVERT(varchar(100), EndTime, 23) as EndTime,CONVERT(varchar(100), UpdateTime, 23) as UpdateTime" +
                ",NodeNum,NodeState,ApplicationState,UserId,UserName,ProjectId,ProStage from o_Process where ProcessId=" + ProcessId;
            try
            {
                var map = dao.GetList(sql, new string[] { "ProcessId", "NodeName", "Content", "Department", "EndTime", "UpdateTime", "NodeNum", "NodeState", "ApplicationState", "UserId", "UserName", "ProjectId", "ProStage" })[0];
                return Json(map);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);

            }
           
        }

        public ActionResult ProcessEditUpdate()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                map["UpdateTime"] = DateTime.Now.ToString();
                string ProcessId = map["ProcessId"].ToString();
                map.Remove("ProcessId");
                dao.update("o_Process", map, "ProcessId=" + ProcessId);
                //if (map["NodeState"].ToString() == "已完成")
                //{
                //    string sql = "update o_Process set ApplicationState=2 where ProcessId=" + ProcessId;
                //    BaseDao.execute(sql);
                //}


                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult ProcessEditDel()
        {
            string ProcessId = Request.Form["ProcessId"] == null ? null : Request.Form["ProcessId"].ToString();
            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            try
            {
                sql = "update o_Process set IsDelete=1 where ProcessId=" + ProcessId;
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);

            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }





        }


        public ActionResult ProcessQuoteTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();


            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,TempName" +
                        "" +
                        " FROM t_d_ProcTemplate" +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "TempName" });
                SqlNum = "select count(*) as TotalNum from ( select TempName FROM t_d_ProcTemplate group by TempName) a";
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /ProcessController/ProcessTemplatTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }


        public ActionResult ProcessQuoteAdd()
        {
            string TempName = Request.Form["TempName"] == null ? null : Request.Form["TempName"].ToString();
            string ProjectId = Request.Form["ProjectId"] == null ? null : Request.Form["ProjectId"].ToString();
            string StartTime = Request.Form["StartTime"] == null ? null : Request.Form["StartTime"].ToString();
            string EndTime = Request.Form["EndTime"] == null ? null : Request.Form["EndTime"].ToString();
            string ProStage = Request.Form["ProStage"] == null ? null : Request.Form["ProStage"].ToString();
            string ProjectType = Request.Form["ProjectType"] == null ? null : Request.Form["ProjectType"].ToString();

            DateTime DStart = DateTime.Parse(StartTime);
            DateTime DEnd = DateTime.Parse(EndTime);

            

            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            try
            {

                sql = "select * from t_d_ProcessManager";
                var ManagerList = dao.GetList(sql,new string[] { "UserId","Department", "ProjectType", "UserName" });
                
                sql = "select * from t_d_ProcTemplate where TempName='" + TempName + "' order by NodeNum ASC";
                var TemplateList = dao.GetList(sql, new string[] { "NodeName", "Content", "Department", "NodeNum" });
                int days = (DEnd - DStart).Days;

                string UserId = "";
                string UserName = "";
                
                if (days < TemplateList.Count)
                {

                    //时间小于排列期
                    sql = "begin ";
                    for (int i = 0; i < TemplateList.Count; i++)
                    {
                        //找到项目经理
                        var ManagerMap = ManagerList.First(t => t["Department"].ToString() == TemplateList[i]["Department"].ToString() &&
                              t["ProjectType"].ToString() == ProjectType
                        );


                        sql += "insert into o_process (NodeName,Content,Department,NodeNum,NodeState,ProjectId,IsDelete,EndTime,UpdateTime,ProStage,UserId,UserName) " +
                            " values('" + TemplateList[i]["NodeName"] + "','"+ TemplateList[i]["Content"] + "','"+ TemplateList[i]["Department"] + "','" +
                            TemplateList[i]["NodeNum"] + "','进行中',"+ ProjectId +",0,'"+ EndTime + "','"+DateTime.Now.ToString("yyyy-MM-dd")+"',"+ ProStage + ","+ ManagerMap["UserId"] + "," +
                            "'"+ ManagerMap["UserName"] + "');";
                    }
                    sql += " end;";
                }
                else
                {
                    //算出时间间隔多少天
                    int AddDaysNum = days / TemplateList.Count;
                    sql = "begin ";
                    for (int i = 0; i < TemplateList.Count; i++)
                    {
                        //找到项目经理
                        var ManagerMap = ManagerList.First(t => t["Department"].ToString() == TemplateList[i]["Department"].ToString() &&
                              t["ProjectType"].ToString() == ProjectType
                        );

                        sql += "insert into o_process (NodeName,Content,Department,NodeNum,NodeState,ProjectId,IsDelete,EndTime,UpdateTime,ProStage,UserId,UserName) " +
                            " values('" + TemplateList[i]["NodeName"] + "','" + TemplateList[i]["Content"] + "','" + TemplateList[i]["Department"] + "','" +
                            TemplateList[i]["NodeNum"] + "','进行中'," + ProjectId + ",0,'" + DEnd.AddDays(-((TemplateList.Count-i-1) * AddDaysNum)).ToString() + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "',"+ ProStage + "" +
                            ","+ ManagerMap["UserId"] + ",'"+ ManagerMap["UserName"] + "');";
                    }
                    sql += " end;";

                }

                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);

            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        /// <summary>
        /// 添加日志文字记录
        /// </summary>
        /// <returns></returns>
        public ActionResult ProcessLogTextAdd()
        {
            string ProcessId = Request.Form["ProcessId"] == null ? null : Request.Form["ProcessId"].ToString();
            string LogContent = Request.Form["LogContent"] == null ? null : Request.Form["LogContent"].ToString();
            string LogType = Request.Form["LogType"] == null ? null : Request.Form["LogType"].ToString();
            //获取用户名
            if (Request.Cookies["UserID"] == null)
            {
                return RedirectToAction("Login", "User");
            }
            string UserID = Request.Cookies["UserID"].Value;
            string UserName = GetUserName(Request.Cookies["UserID"].Value);

            Dictionary<string, object> result = new Dictionary<string, object>();
            string sql = "";
            sql = "insert into o_processLog (LogContent,LogType,ProcessId,LogTime,UserId,UserName) values ('" + LogContent + "','" + LogType + "'," + ProcessId + "" +
                ",'" + DateTime.Now.ToString() + "'," + UserID + ",'" + UserName + "')";
            try
            {
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        /// <summary>
        /// 获取节点日志记录
        /// </summary>
        /// <returns></returns>
        public ActionResult ProcessGetLog()
        {
            string ProcessId = Request.Form["ProcessId"] == null ? null : Request.Form["ProcessId"].ToString();
            string sql = "select UserName,ProcessLogId,LogContent,LogType,ProcessId,CONVERT(varchar(100), LogTime, 23) as LogTime from o_ProcessLog where ProcessId=" + ProcessId + " order by ProcessLogId Desc";

            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                var LogList = dao.GetList(sql, new string[] { "UserName","ProcessLogId", "LogContent", "LogType", "LogTime", "ProcessId" });
                return Json(LogList);
            }
            catch (Exception e)
            {

                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        private string GetUserName(string UserID)
        {
            string Sql = "select UserName from t_d_user where UserID='" + UserID + "'";
            List<Dictionary<string, object>> UserList = new List<Dictionary<string, object>>();
            try
            {
                UserList = dao.GetList(Sql, new string[] { "UserName" });
                string UserName = UserList[0]["UserName"].ToString();
                return UserName;
            }
            catch (Exception)
            {

                return "Error";
            }

        }

        /// <summary>
        /// 申请完结 驳回操作
        /// </summary>
        /// <returns></returns>
        public ActionResult ProcessAppState()
        {
            string ProcessId = Request.Form["ProcessId"] == null ? null : Request.Form["ProcessId"].ToString();
            string Value = Request.Form["Value"] == null ? null : Request.Form["Value"].ToString();


            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                string sql = "update o_Process set ApplicationState=" + Value + " where ProcessId=" + ProcessId;
                BaseDao.execute(sql);

                string UserName = GetUserName(Request.Cookies["UserID"].Value);
                string LogContent = "";
                if (Value == "1")
                {
                    LogContent = "提交“申请完结”";
                }
                else if(Value == "0")
                {
                    LogContent = "确认“驳回申请”";
                }
                sql = "insert into o_processLog (LogContent,LogType,ProcessId,LogTime,UserId,UserName) values ('" + LogContent + "','内容变更'," + ProcessId + "" +
                    ",'" + DateTime.Now.ToString() + "'," + Request.Cookies["UserID"].Value + ",'" + UserName + "')";
                BaseDao.execute(sql);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult ProgressInfo()
        {
            string ProjectName = Request.QueryString["ProjectName"] ?? null;
            string ProjectType = Request.QueryString["ProjectType"] ?? null;
            string ProjectYear = Request.QueryString["ProjectYear"] ?? null;
            string Condition = "";
            if (ProjectName != null)
            {
                Condition += " and b.Name like '%" + ProjectName + "%'";
            }
            if(ProjectType != null)
            {
                Condition += " and b.Type='" + ProjectType + "'";
            }
            if(ProjectYear != null)
            {
                Condition += " and b.ContrTime like '%" + ProjectYear + "%'";
            }

            string sql = "SELECT a.ProjectId,a.NodeState,CONVERT(varchar(100), b.ContrTime, 23) as ContrTime,datepart(yyyy,b.ContrTime) as ContrYear,";
            sql += " b.Name from o_Process a INNER JOIN t_d_ProjectInfo b ON a.ProjectId=b.projectId and b.IsDelete=0" + Condition;
            sql += " where a.IsDelete<>1";
            sql += " ORDER BY b.projectId,b.ContrTime DESC";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "NodeState", "ContrTime", "ContrYear", "Name" });
            string tempProjectId = "-1";
            List<Dictionary<string, object>> ListInfo = new List<Dictionary<string, object>>();
            int JXZ = 0;    //进行中
            int YWC = 0;    //已完成
            int ZH = 0;     //滞后
            int tempNum = 0;//计数
            for (int i = 0; i < ProjectList.Count; i++)
            {
                if (tempProjectId != ProjectList[i]["ProjectId"].ToString())
                {//新增项目的情况
                    //计数缓冲清0
                    JXZ = 0;YWC = 0;ZH = 0;
                    Dictionary<string, object> map = new Dictionary<string, object>()
                    {
                        ["ProjectId"] = ProjectList[i]["ProjectId"].ToString(),
                        ["JXZ"] = 0,
                        ["YWC"] = 0,
                        ["ZH"] = 0,
                        ["ContrTime"] = ProjectList[i]["ContrTime"].ToString(),
                        ["ContrYear"] = ProjectList[i]["ContrYear"].ToString(),
                        ["Name"] = ProjectList[i]["Name"].ToString(),
                    };
                    ListInfo.Add(map);

                    if ("进行中" == ProjectList[i]["NodeState"].ToString())
                    {
                        JXZ++;
                    }
                    if ("已完成" == ProjectList[i]["NodeState"].ToString())
                    {
                        YWC++;
                    }
                    if ("滞后" == ProjectList[i]["NodeState"].ToString())
                    {
                        ZH++;
                    }
                    ListInfo[tempNum]["JXZ"] = JXZ;
                    ListInfo[tempNum]["YWC"] = YWC;
                    ListInfo[tempNum]["ZH"] = ZH;
                    tempNum++;
                    tempProjectId = ProjectList[i]["ProjectId"].ToString();
                }
                else
                {
                    if ("进行中" == ProjectList[i]["NodeState"].ToString())
                    {
                        JXZ++;
                    }
                    if ("已完成" == ProjectList[i]["NodeState"].ToString())
                    {
                        YWC++;
                    }
                    if ("滞后" == ProjectList[i]["NodeState"].ToString())
                    {
                        ZH++;
                    }
                    ListInfo[tempNum-1]["JXZ"] = JXZ;
                    ListInfo[tempNum-1]["YWC"] = YWC;
                    ListInfo[tempNum-1]["ZH"] = ZH;
                    
                }
                
                
            }

            ViewBag.ListInfo = ListInfo;


            return View("ProgressInfo");
        }


        /// <summary>
        /// 主业工程 项目部署VIEW
        /// </summary>
        /// <returns></returns>
        public ActionResult ZYArrangeView()
        {
            string ProjectId = Request.QueryString["ProjectId"] == null ? null : Request.QueryString["ProjectId"].ToString();
            string ProStage = Request.QueryString["ProStage"] == null ? null : Request.QueryString["ProStage"].ToString();

            string sql = "select ProjectId,Name,ProjectCode,Type from t_d_ProjectInfo where IsDelete<>1 and Type='主业'";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "Name", "ProjectCode", "Type" });
            ViewBag.ProjectList = ProjectList;

            if (ProjectId == null || ProjectId == "")
            {
                ViewBag.ProjectId = "";
                ViewBag.Type = "主业";
                
            }
            else
            {
                ViewBag.ProjectId = ProjectId;
                //ViewBag.Type = ProjectList.First(t => t["ProjectId"].ToString() == ProjectId)["Type"].ToString();
                ViewBag.Type = ProjectList.First(t => t["ProjectId"].ToString() == ProjectId)["Type"].ToString();
            }

            if (ProStage ==null || ProStage == "")
            {
                ViewBag.ProStage = "1";
            }
            else
            {
                ViewBag.ProStage = ProStage;
            }

            sql = "select UserId,UserName from t_d_User where Department<>'领导' and Department<>'开发者' and IsDelete<>1 order by Department";
            var UserList = dao.GetList(sql, new string[] { "UserId", "UserName" });
            ViewBag.UserList = UserList;

            string UserId = Request.Cookies["UserID"].Value;
            sql = "select * from o_Authority where UserId=" + UserId;
            var AuthList = dao.GetList(sql, new string[] { "Type", "Name", "UserId" });
            ViewBag.AuthList = AuthList;
            ViewBag.UserId = UserId;


            return View("ZYArrange");
        }

        /// <summary>
        /// 用户工程 部署VIEW
        /// </summary>
        /// <returns></returns>
        public ActionResult YHGCArrangeView()
        {
            string ProjectId = Request.QueryString["ProjectId"] == null ? null : Request.QueryString["ProjectId"].ToString();
            string ProStage = Request.QueryString["ProStage"] == null ? null : Request.QueryString["ProStage"].ToString();

            string sql = "select ProjectId,Name,ProjectCode,Type from t_d_ProjectInfo where IsDelete<>1 and Type='用户工程'";
            var ProjectList = dao.GetList(sql, new string[] { "ProjectId", "Name", "ProjectCode", "Type" });
            ViewBag.ProjectList = ProjectList;

            if (ProjectId == null || ProjectId == "")
            {
                ViewBag.ProjectId = "";
                ViewBag.Type = "用户工程";

            }
            else
            {
                ViewBag.ProjectId = ProjectId;
                //ViewBag.Type = ProjectList.First(t => t["ProjectId"].ToString() == ProjectId)["Type"].ToString();
                ViewBag.Type = ProjectList.First(t => t["ProjectId"].ToString() == ProjectId)["Type"].ToString();
            }

            if (ProStage == null || ProStage == "")
            {
                ViewBag.ProStage = "1";
            }
            else
            {
                ViewBag.ProStage = ProStage;
            }

            sql = "select UserId,UserName from t_d_User where Department<>'领导' and Department<>'开发者' and IsDelete<>1 order by Department";
            var UserList = dao.GetList(sql, new string[] { "UserId", "UserName" });
            ViewBag.UserList = UserList;

            string UserId = Request.Cookies["UserID"].Value;
            sql = "select * from o_Authority where UserId=" + UserId;
            var AuthList = dao.GetList(sql, new string[] { "Type", "Name", "UserId" });
            ViewBag.AuthList = AuthList;
            ViewBag.UserId = UserId;


            return View("YHGCArrange");
        }




    }
}